import os
import sys
import time
import random
import math
import subprocess
import logging
import pyautogui
import pyperclip
import winreg
from mcp.server.fastmcp import FastMCP

# 设置Windows控制台UTF-8编码
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')

# 初始化FastMCP服务器
mcp = FastMCP()

# 配置日志
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# 预设程序路径
try:
    preset_programs = {}
    # 尝试从文件中加载预设程序路径
    if os.path.exists('程序预设.txt'):
        with open('程序预设.txt', 'r', encoding='utf-8') as f:
            for line in f:
                if '=' in line:
                    key, value = line.strip().split('=', 1)
                    preset_programs[key] = value
    
    # 预设命令路径
    preset_commands = {}
    if os.path.exists('命令预设.txt'):
        with open('命令预设.txt', 'r', encoding='utf-8') as f:
            for line in f:
                if '=' in line:
                    key, value = line.strip().split('=', 1)
                    preset_commands[key] = value
except Exception as e:
    logger.error(f"加载预设文件失败: {str(e)}")
    preset_programs = {}
    preset_commands = {}

# 检查是否允许使用微信工具
允许使用微信发消息工具 = False
微信工具判断文件路径 = os.path.join(os.path.dirname(os.path.abspath(__file__)), "微信发消息工具允许使用.DLL")
if os.path.exists(微信工具判断文件路径):
    允许使用微信发消息工具 = True

# 计算器工具
@mcp.tool()
def calculator(expression: str) -> dict:
    """
    计算数学表达式
    参数：
    expression: 数学表达式字符串，例如 "2 + 3 * 4"
    """
    try:
        # 安全执行表达式计算
        allowed_globals = {"__builtins__": {}, "math": math, "random": random}
        result = eval(expression, allowed_globals)
        return {"result": result}
    except Exception as e:
        logger.error(f"计算错误: {str(e)}")
        return {"error": str(e)}

# 运行电脑程序
@mcp.tool()
def run_program(program_name: str) -> dict:
    """
    运行电脑端程序
    参数：
    program_name: 预设软件名称或具体程序路径
    """
    try:
        # 如果是预设程序名称，则获取对应的路径
        if program_name in preset_programs:
            program_path = preset_programs[program_name]
        else:
            program_path = program_name
        
        # 执行程序
        if program_path.endswith('.lnk'):
            # 如果是.lnk文件，使用os.startfile打开
            os.startfile(program_path)
        else:
            # 否则使用subprocess打开
            subprocess.Popen(program_path)
        
        logger.info(f"已运行程序: {program_name}")
        return {"是否成功": True, "结果": f"已运行程序: {program_name}"}
    except Exception as e:
        logger.error(f"运行程序失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 使用指定程序打开指定文件
@mcp.tool()
def open_file_with_program(program_name: str, file_path: str) -> dict:
    """
    使用指定程序打开指定文件
    参数：
    program_name: 预设软件名称或具体程序路径
    file_path: 要打开的文件路径
    """
    try:
        # 验证文件是否存在
        if not os.path.exists(file_path):
            return {"是否成功": False, "错误": f"文件不存在: {file_path}"}
        
        # 获取程序路径
        program_path = None
        
        # 1. 先检查是否在预设程序中
        if program_name in preset_programs:
            program_path = preset_programs[program_name]
        # 2. 如果是常见程序名称，尝试自动查找路径
        elif program_name.lower() in ["word", "microsoft word", "msword"]:
            # 尝试从常见路径查找Word
            common_word_paths = [
                r"C:\Program Files\Microsoft Office\Office16\WINWORD.EXE",
                r"C:\Program Files (x86)\Microsoft Office\Office16\WINWORD.EXE",
                r"C:\Program Files\Microsoft Office\Office15\WINWORD.EXE",
                r"C:\Program Files (x86)\Microsoft Office\Office15\WINWORD.EXE",
                r"C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE",
                r"C:\Program Files\Microsoft Office\root\Office15\WINWORD.EXE"
            ]
            for path in common_word_paths:
                if os.path.exists(path):
                    program_path = path
                    break
            # 如果找不到，尝试从注册表获取
            if not program_path:
                try:
                    key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WINWORD.EXE'
                    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as key:
                        program_path = winreg.QueryValue(key, None)
                except:
                    pass
        elif program_name.lower() in ["excel", "microsoft excel", "msexcel"]:
            # 尝试从常见路径查找Excel
            common_excel_paths = [
                r"C:\Program Files\Microsoft Office\Office16\EXCEL.EXE",
                r"C:\Program Files (x86)\Microsoft Office\Office16\EXCEL.EXE",
                r"C:\Program Files\Microsoft Office\Office15\EXCEL.EXE",
                r"C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE",
                r"C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE",
                r"C:\Program Files\Microsoft Office\root\Office15\EXCEL.EXE"
            ]
            for path in common_excel_paths:
                if os.path.exists(path):
                    program_path = path
                    break
            # 如果找不到，尝试从注册表获取
            if not program_path:
                try:
                    key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\EXCEL.EXE'
                    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as key:
                        program_path = winreg.QueryValue(key, None)
                except:
                    pass
        elif program_name.lower() in ["powerpoint", "ppt", "microsoft powerpoint", "msppt"]:
            # 尝试从常见路径查找PowerPoint
            common_ppt_paths = [
                r"C:\Program Files\Microsoft Office\Office16\POWERPNT.EXE",
                r"C:\Program Files (x86)\Microsoft Office\Office16\POWERPNT.EXE",
                r"C:\Program Files\Microsoft Office\Office15\POWERPNT.EXE",
                r"C:\Program Files (x86)\Microsoft Office\Office15\POWERPNT.EXE",
                r"C:\Program Files\Microsoft Office\root\Office16\POWERPNT.EXE",
                r"C:\Program Files\Microsoft Office\root\Office15\POWERPNT.EXE"
            ]
            for path in common_ppt_paths:
                if os.path.exists(path):
                    program_path = path
                    break
            # 如果找不到，尝试从注册表获取
            if not program_path:
                try:
                    key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\POWERPNT.EXE'
                    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as key:
                        program_path = winreg.QueryValue(key, None)
                except:
                    pass
        elif program_name.lower() in ["photoshop", "adobe photoshop", "ps"]:
            # 尝试从常见路径查找Photoshop
            common_ps_paths = [
                r"C:\Program Files\Adobe\Adobe Photoshop 2024\Photoshop.exe",
                r"C:\Program Files\Adobe\Adobe Photoshop 2023\Photoshop.exe",
                r"C:\Program Files\Adobe\Adobe Photoshop 2022\Photoshop.exe",
                r"C:\Program Files\Adobe\Adobe Photoshop 2021\Photoshop.exe",
                r"C:\Program Files\Adobe\Adobe Photoshop CC 2019\Photoshop.exe",
                r"C:\Program Files\Adobe\Adobe Photoshop CC 2020\Photoshop.exe",
                r"C:\Program Files\Adobe\Adobe Photoshop CC 2018\Photoshop.exe"
            ]
            for path in common_ps_paths:
                if os.path.exists(path):
                    program_path = path
                    break
            # 如果找不到，尝试从注册表获取
            if not program_path:
                try:
                    key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Photoshop.exe'
                    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as key:
                        program_path = winreg.QueryValue(key, None)
                except:
                    pass
        elif program_name.lower() in ["acrobat", "adobe acrobat", "pdf", "adobe reader"]:
            # 尝试从常见路径查找Adobe Acrobat
            common_acrobat_paths = [
                r"C:\Program Files\Adobe\Acrobat DC\Acrobat\Acrobat.exe",
                r"C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe",
                r"C:\Program Files\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe",
                r"C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat.exe",
                r"C:\Program Files\Adobe\Acrobat 2023\Acrobat\Acrobat.exe",
                r"C:\Program Files (x86)\Adobe\Acrobat 2020\Acrobat\Acrobat.exe"
            ]
            for path in common_acrobat_paths:
                if os.path.exists(path):
                    program_path = path
                    break
            # 如果找不到，尝试从注册表获取
            if not program_path:
                try:
                    key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Acrobat.exe'
                    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as key:
                        program_path = winreg.QueryValue(key, None)
                except:
                    try:
                        key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\AcroRd32.exe'
                        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) as key:
                            program_path = winreg.QueryValue(key, None)
                    except:
                        pass
        elif program_name.lower() == "notepad":
            program_path = "notepad.exe"
        # 3. 如果以上都没找到，使用用户提供的程序名
        else:
            program_path = program_name
        
        # 记录日志
        logger.info(f"尝试使用{program_path}打开文件{file_path}")
        
        # 使用Windows默认打开方式作为备选
        try:
            # 方式1：如果有明确的程序路径，尝试直接打开
            if program_path and os.path.exists(program_path):
                # 对于可执行文件，尝试不同的打开方式
                try:
                    # 使用shell=True执行
                    cmd = f'"{program_path}" "{file_path}"'
                    subprocess.run(cmd, shell=True, check=False)
                    logger.info(f"已使用指定程序路径打开文件")
                    return {"是否成功": True, "结果": f"已使用{program_name}打开文件: {file_path}"}
                except Exception as e:
                    logger.warning(f"直接执行失败: {str(e)}")
            
            # 方式2：使用Windows的start命令，这是最通用的方式
            if program_path:
                try:
                    cmd = f'start "" "{program_path}" "{file_path}"'
                    subprocess.run(cmd, shell=True, check=False)
                    logger.info(f"已使用start命令打开文件")
                    return {"是否成功": True, "结果": f"已使用{program_name}打开文件: {file_path}"}
                except Exception as e:
                    logger.warning(f"start命令失败: {str(e)}")
            
            # 方式3：如果程序名是通用的，尝试直接用程序名
            if not os.path.exists(program_path):
                try:
                    cmd = f'start "" "{program_name}" "{file_path}"'
                    subprocess.run(cmd, shell=True, check=False)
                    logger.info(f"已使用程序名打开文件")
                    return {"是否成功": True, "结果": f"已使用{program_name}打开文件: {file_path}"}
                except Exception as e:
                    logger.warning(f"使用程序名失败: {str(e)}")
            
            # 方式4：作为最后的备选，使用Windows默认打开方式
            try:
                os.startfile(file_path)
                logger.info(f"已使用默认程序打开文件")
                return {"是否成功": True, "结果": f"已使用默认程序打开文件: {file_path}"}
            except Exception as e:
                logger.error(f"默认打开方式也失败: {str(e)}")
                return {"是否成功": False, "错误": f"无法打开文件: {str(e)}"}
                
        except Exception as e:
            # 捕获所有异常，确保服务不会崩溃
            error_msg = str(e).encode('utf-8', errors='replace').decode('utf-8')
            logger.error(f"打开文件过程中出错: {error_msg}")
            return {"是否成功": False, "错误": f"操作失败: {error_msg}"}
    except Exception as e:
        # 捕获所有异常，确保服务不会崩溃
        error_msg = str(e).encode('utf-8', errors='replace').decode('utf-8')
        logger.error(f"使用程序打开文件失败: {error_msg}")
        return {"是否成功": False, "错误": f"操作失败: {error_msg}"}

# 打开URL网址
@mcp.tool()
def open_url(url: str) -> dict:
    """
    在默认浏览器中打开URL网址
    参数：
    url: 网址字符串，例如 "https://www.baidu.com"
    """
    try:
        # 确保URL格式正确
        if not url.startswith(('http://', 'https://')):
            url = 'https://' + url
        
        # 使用默认浏览器打开
        os.startfile(url)
        logger.info(f"已打开网址: {url}")
        return {"是否成功": True, "结果": f"已打开网址: {url}"}
    except Exception as e:
        logger.error(f"打开网址失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 运行CMD命令
@mcp.tool()
def run_cmd_command(command: str) -> dict:
    """
    在电脑上运行CMD命令
    参数：
    command: 预设命令或具体CMD命令
    """
    try:
        # 如果是预设命令，则获取对应的实际命令
        if command in preset_commands:
            actual_command = preset_commands[command]
        else:
            actual_command = command
        
        # 执行命令
        result = subprocess.run(actual_command, shell=True, capture_output=True, text=True, timeout=30)
        output = result.stdout if result.returncode == 0 else result.stderr
        
        logger.info(f"已执行命令: {command}")
        return {"是否成功": True, "结果": output[:1000]}
    except subprocess.TimeoutExpired:
        logger.error("命令执行超时")
        return {"是否成功": False, "错误": "命令执行超时"}
    except Exception as e:
        logger.error(f"执行命令失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 创建文件写入内容
@mcp.tool()
def create_file(file_path: str, content: str) -> dict:
    """
    创建文件并写入内容
    参数：
    file_path: 文件路径
    content: 要写入的内容
    """
    try:
        # 确保目录存在
        directory = os.path.dirname(file_path)
        if directory and not os.path.exists(directory):
            os.makedirs(directory)
        
        # 写入文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        logger.info(f"已创建文件: {file_path}")
        return {"是否成功": True, "结果": f"已创建文件: {file_path}"}
    except Exception as e:
        logger.error(f"创建文件失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 读取复制内容
@mcp.tool()
def read_clipboard() -> dict:
    """
    读取剪贴板内容
    """
    try:
        content = pyperclip.paste()
        logger.info("已读取剪贴板内容")
        return {"是否成功": True, "结果": content}
    except Exception as e:
        logger.error(f"读取剪贴板失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 写入填入内容
@mcp.tool()
def write_and_paste(content: str) -> dict:
    """
    将内容复制到剪贴板并模拟Ctrl+V粘贴
    参数：
    content: 要粘贴的内容
    """
    try:
        # 复制内容到剪贴板
        pyperclip.copy(content)
        time.sleep(0.1)
        # 模拟Ctrl+V粘贴
        pyautogui.hotkey('ctrl', 'v')
        logger.info("已粘贴内容")
        return {"是否成功": True, "结果": "已粘贴内容"}
    except Exception as e:
        logger.error(f"粘贴内容失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 回车发送
@mcp.tool()
def press_enter() -> dict:
    """
    模拟按下Enter键
    """
    try:
        pyautogui.press('enter')
        logger.info("已按下Enter键")
        return {"是否成功": True, "结果": "已按下Enter键"}
    except Exception as e:
        logger.error(f"操作失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 撤销操作
@mcp.tool()
def undo_operation() -> dict:
    """
    模拟按下Ctrl+Z撤销操作
    """
    try:
        pyautogui.hotkey('ctrl', 'z')
        logger.info("已执行撤销操作")
        return {"是否成功": True, "结果": "已执行撤销操作"}
    except Exception as e:
        logger.error(f"撤销操作失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 锁定电脑
@mcp.tool()
def lock_computer() -> dict:
    """
    锁定计算机
    """
    try:
        subprocess.call('rundll32.exe user32.dll,LockWorkStation')
        logger.info("已锁定电脑")
        return {"是否成功": True, "结果": "已锁定电脑"}
    except Exception as e:
        logger.error(f"锁定电脑失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 电脑关机计划
@mcp.tool()
def schedule_shutdown(minutes: int) -> dict:
    """
    设置电脑定时关机
    参数：
    minutes: 多少分钟后关机
    """
    try:
        # 转换为秒
        seconds = minutes * 60
        # 执行关机命令
        subprocess.run(f'shutdown -s -t {seconds}', shell=True)
        logger.info(f"已设置{minutes}分钟后关机")
        return {"是否成功": True, "结果": f"已设置{minutes}分钟后关机"}
    except Exception as e:
        logger.error(f"设置关机失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 设置电脑音量
@mcp.tool()
def set_volume(volume_level: int) -> dict:
    """
    设置电脑系统音量
    参数：
    volume_level: 音量级别，0-100
    """
    try:
        # 确保音量级别在有效范围内
        volume_level = max(0, min(100, volume_level))
        
        # 使用pycaw库设置音量（如果可用）
        try:
            from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
            from comtypes import CLSCTX_ALL
            
            devices = AudioUtilities.GetSpeakers()
            interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
            volume = interface.QueryInterface(IAudioEndpointVolume)
            volume.SetMasterVolumeLevelScalar(volume_level / 100, None)
            success = True
        except ImportError:
            # 如果pycaw不可用，使用命令行方式
            subprocess.run(f'nircmd setsysvolume {int(volume_level * 655.35)}', shell=True, capture_output=True)
            success = True
        
        if success:
            logger.info(f"已设置音量为{volume_level}%")
            return {"是否成功": True, "结果": f"已设置音量为{volume_level}%"}
    except Exception as e:
        logger.error(f"设置音量失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 系统截图
@mcp.tool()
def take_screenshot(area: str = "全屏") -> dict:
    """
    调用系统截图工具
    参数：
    area: 截图区域，可选"全屏"或"区域"
    """
    try:
        if area == "区域":
            # 调用Windows自带的区域截图工具
            subprocess.Popen(['snippingtool', '/clip'])
        else:
            # 全屏截图
            pyautogui.screenshot().save('screenshot.png')
        
        logger.info(f"已执行{area}截图")
        return {"是否成功": True, "结果": f"已执行{area}截图"}
    except Exception as e:
        logger.error(f"截图失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 显示桌面
@mcp.tool()
def show_desktop() -> dict:
    """
    显示桌面（模拟Win+D）
    """
    try:
        pyautogui.hotkey('win', 'd')
        logger.info("已显示桌面")
        return {"是否成功": True, "结果": "已显示桌面"}
    except Exception as e:
        logger.error(f"显示桌面失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 查看系统资源使用情况
@mcp.tool()
def check_system_resources() -> dict:
    """
    查看系统资源使用情况（CPU、内存、磁盘）
    """
    try:
        # 使用wmic命令获取系统信息
        cpu_info = subprocess.run('wmic cpu get loadpercentage', shell=True, capture_output=True, text=True).stdout
        memory_info = subprocess.run('wmic OS get FreePhysicalMemory,TotalVisibleMemorySize', shell=True, capture_output=True, text=True).stdout
        disk_info = subprocess.run('wmic logicaldisk get size,freespace,caption', shell=True, capture_output=True, text=True).stdout
        
        # 格式化结果
        result = f"CPU使用率: {cpu_info.strip().split('\n')[-1] if cpu_info else '未知'}%\n"
        result += f"内存信息:\n{memory_info}\n"
        result += f"磁盘信息:\n{disk_info}"
        
        logger.info("已获取系统资源信息")
        return {"是否成功": True, "结果": result[:1000]}
    except Exception as e:
        logger.error(f"获取系统资源信息失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 查看电脑配置信息
@mcp.tool()
def check_computer_info() -> dict:
    """
    查看电脑配置信息
    """
    try:
        # 获取系统信息
        system_info = subprocess.run('systeminfo', shell=True, capture_output=True, text=True, timeout=60).stdout
        
        # 获取桌面路径
        desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
        
        result = f"电脑配置信息:\n{system_info.split('\n')[0:20]}\n\n"
        result += f"桌面路径: {desktop_path}"
        
        logger.info("已获取电脑配置信息")
        return {"是否成功": True, "结果": result[:1000]}
    except subprocess.TimeoutExpired:
        logger.error("获取电脑配置信息超时")
        return {"是否成功": False, "错误": "获取电脑配置信息超时"}
    except Exception as e:
        logger.error(f"获取电脑配置信息失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 微信消息发送工具
@mcp.tool()
def send_wechat_message(contact_name: str, message: str) -> dict:
    """
    向微信指定联系人发送消息
    参数：
    contact_name: 联系人名称
    message: 要发送的消息内容
    """
    try:
        # 检查是否允许使用微信工具
        if not 允许使用微信发消息工具:
            return {"是否成功": False, "错误": "未开启微信消息发送功能"}
        
        # 模拟微信操作（简化版）
        # 1. 确保微信打开
        program_path = preset_programs.get("微信", "微信")
        if program_path.endswith('.lnk'):
            os.startfile(program_path)
        else:
            subprocess.Popen(program_path)
        time.sleep(1)
        
        # 2. 使用快捷键打开搜索框
        pyautogui.hotkey('ctrl', 'f')
        time.sleep(0.5)
        
        # 3. 输入联系人名称
        pyperclip.copy(contact_name)
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(0.5)
        pyautogui.press('enter')
        time.sleep(0.5)
        
        # 4. 输入并发送消息
        pyperclip.copy(message)
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(0.5)
        pyautogui.press('enter')
        
        logger.info(f"已向{contact_name}发送微信消息")
        return {"是否成功": True, "结果": f"已向{contact_name}发送微信消息"}
    except Exception as e:
        logger.error(f"发送微信消息失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 设置系统主题
@mcp.tool()
def set_system_theme(theme_type: str = "深色") -> dict:
    """
    设置Windows系统深浅色主题
    参数：
    theme_type: 主题类型，可选"深色"或"浅色"
    """
    try:
        # 设置注册表项
        key_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize'
        value_name = 'AppsUseLightTheme'
        value_data = 0 if theme_type == "深色" else 1
        
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE) as key:
            winreg.SetValueEx(key, value_name, 0, winreg.REG_DWORD, value_data)
        
        logger.info(f"已设置系统主题为{theme_type}")
        return {"是否成功": True, "结果": f"已设置系统主题为{theme_type}"}
    except Exception as e:
        logger.error(f"设置系统主题失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 更换桌面壁纸
@mcp.tool()
def change_wallpaper(image_url: str = "") -> dict:
    """
    更换桌面壁纸
    参数：
    image_url: 壁纸图片URL（可选）
    """
    try:
        if image_url:
            # 如果提供了URL，下载图片
            import requests
            local_path = 'wallpaper.jpg'
            response = requests.get(image_url, timeout=30)
            with open(local_path, 'wb') as f:
                f.write(response.content)
        else:
            # 否则使用默认壁纸
            local_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'wallpaper.jpg')
        
        # 设置壁纸
        subprocess.run(f'reg add "HKCU\\Control Panel\\Desktop" /v Wallpaper /t REG_SZ /d "{local_path}" /f', shell=True)
        subprocess.run('RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters', shell=True)
        
        logger.info("已更换桌面壁纸")
        return {"是否成功": True, "结果": "已更换桌面壁纸"}
    except Exception as e:
        logger.error(f"更换桌面壁纸失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# PPT控制工具
@mcp.tool()
def ppt_previous() -> dict:
    """
    PPT上一页
    """
    try:
        pyautogui.press('left')
        logger.info("已执行PPT上一页")
        return {"是否成功": True, "结果": "已执行PPT上一页"}
    except Exception as e:
        logger.error(f"PPT操作失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

@mcp.tool()
def ppt_next() -> dict:
    """
    PPT下一页
    """
    try:
        pyautogui.press('right')
        logger.info("已执行PPT下一页")
        return {"是否成功": True, "结果": "已执行PPT下一页"}
    except Exception as e:
        logger.error(f"PPT操作失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

@mcp.tool()
def ppt_end_slideshow() -> dict:
    """
    PPT结束放映
    """
    try:
        pyautogui.press('esc')
        logger.info("已结束PPT放映")
        return {"是否成功": True, "结果": "已结束PPT放映"}
    except Exception as e:
        logger.error(f"PPT操作失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

@mcp.tool()
def ppt_start_from_current() -> dict:
    """
    PPT从当前页开始放映
    """
    try:
        pyautogui.hotkey('shift', 'f5')
        logger.info("已从当前页开始PPT放映")
        return {"是否成功": True, "结果": "已从当前页开始PPT放映"}
    except Exception as e:
        logger.error(f"PPT操作失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

@mcp.tool()
def ppt_start_from_beginning() -> dict:
    """
    PPT从头开始放映
    """
    try:
        pyautogui.press('f5')
        logger.info("已从头开始PPT放映")
        return {"是否成功": True, "结果": "已从头开始PPT放映"}
    except Exception as e:
        logger.error(f"PPT操作失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 在文档上查找内容
@mcp.tool()
def find_text_in_document(search_text: str) -> dict:
    """
    在文档中查找内容
    参数：
    search_text: 要查找的文本
    """
    try:
        # 模拟Ctrl+F
        pyautogui.hotkey('ctrl', 'f')
        time.sleep(0.5)
        # 输入搜索内容
        pyperclip.copy(search_text)
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(0.5)
        # 执行搜索
        pyautogui.press('enter')
        
        logger.info(f"已在文档中查找: {search_text}")
        return {"是否成功": True, "结果": f"已在文档中查找: {search_text}"}
    except Exception as e:
        logger.error(f"文档搜索失败: {str(e)}")
        return {"是否成功": False, "错误": str(e)}

# 主程序入口
if __name__ == "__main__":
    logger.info("\n\n\tWindows控制服务已启动！等待调用！\n\n")
    mcp.run(transport="stdio")